const strUtilFile = require("../../utils/strUtil.js");
const strUtil = strUtilFile.strUtil;
const requestFile = require("../../utils/request.js");
const request = requestFile.request;
const routerFile = require("../../utils/router.js");
const router = routerFile.router;
const toastFile = require("../../utils/notice.js");
const Toast = toastFile.Toast;
const securityFile = require("../../utils/security.js");
const security = securityFile.security;
const constantFile = require("../../utils/constant.js");
const constant = constantFile.constant;

Page({

  data: {
    programHeader: "../../images/program-header.jpg",
  },

  handleLogin: function(e) {
    Toast.loading("登录中")
    
    const {username, password} = e.detail.value;
    // 这里对用户名和密码格式进行校验（不能为空）
    if(!strUtil.strCanUse(username)) {
      Toast.notify("请输入账户！")
      return;
    } else if (!strUtil.strCanUse(password)) {
      Toast.notify("密码不能为空！")
      return;
    }
    // 校验账户 (纯数字)
    var checkPattern = /[0-9]{8,15}/
    if (!checkPattern.test(username)) {
      Toast.fail("用户名不合法！")
      return;
    }

    // 向微信服务器请求jsCode
    wx.login({
      timeout: 60 * 1000,
    }).then (
      function(res) {
        const code = res.code;

        // 密码加密
        const encryPass = security.md5(password);

        // 向后端发起请求来判断登录
        const loginUri = router.userLogin;
        request(loginUri, "POST", {
          username: username,
          password: encryPass,
          code: code,
        }).then(res => {
          // 请求成功
          const resp = res.data;
          if (resp != undefined && resp != null) {
            const {code, message, data} = resp;
            if (code == 200) {
              // 登录成功，将获取到的用户唯一凭证信息和权限信息保存到缓存
              wx.setStorageSync('user', data.user);
              wx.setStorageSync('auth', data.auth);
              wx.setStorageSync('desc', data.desc);
              wx.setStorageSync('isLogin', true);
              const hasMail = data.hasMail;
              if (!hasMail) {
                wx.navigateTo({
                  url: '../bindMail/bindMail',
                  events: {
                    onMailBinded: function(data) {
                      wx.navigateBack({
                        delta: 1,
                      })
                    }
                  }
                })
              } else {
                wx.navigateBack({
                  delta: 1,
                })
              }
            } else {
              // 登录失败，输出打印到控制台并提示用户相关信息
              Toast.fail("账户名或密码错误！");
            }
          }
        }).catch(errMsg => {
          Toast.fail("网络异常！");
        })
      }
    ).catch (
      function (errMsg) {
        wx.showToast({
          title: '网络请求失败！',
          icon: 'error',
        })
      }
    );
    
  }
})